package cn.com.dashihui.web.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class SubString extends TagSupport{
	private static final long serialVersionUID = 1L;
	private String string;
	private int limit;
	private boolean clearHTML = false;
	
	public void setString(String string){
		this.string = string;
	}
	
	public void setLimit(int limit){
		this.limit = limit;
	}
	
	public void setClearHTML(boolean clearHTML) {
		this.clearHTML = clearHTML;
	}
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = this.pageContext.getOut();
		try {
			if(clearHTML){
				string = clearHTML(string);
			}
			out.print(substring(string,limit));
		} catch (Exception e) { 
			e.printStackTrace(); 
		}
		return super.doStartTag();
	}
	
	public static String substring(String str,int limit){
		if(StringUtils.isNotBlank(str)&&limit>0){
			if(str.length()<=limit){
				return str;
			}else{
				String tmp = str.substring(0, limit);
				if(tmp.endsWith(",")||tmp.endsWith("，")||tmp.endsWith(".")||tmp.endsWith("。")){
					tmp = tmp.substring(0, tmp.length()-1);
				}
				tmp = tmp.replace("\n", "").replace("\t", "");
				return tmp+"...";
			}
		}else{
			return str;
		}
	}
	
	public static String clearHTML(String htmlStr) {
		Document doc = Jsoup.parse(htmlStr);
		return doc.text();
//		Pattern p_script,p_style,p_html;
//		Matcher m_script,m_style,m_html;
//		try {
//			//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
//			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
//			//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
//			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
//			//定义HTML标签的正则表达式
//			String regEx_html = "<[^>]+>";
//			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
//			m_script = p_script.matcher(htmlStr);
//			//过滤script标签
//			htmlStr = m_script.replaceAll("");
//			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
//			m_style = p_style.matcher(htmlStr);
//			//过滤style标签
//			htmlStr = m_style.replaceAll("");
//			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
//			m_html = p_html.matcher(htmlStr);
//			//过滤html标签
//			htmlStr = m_html.replaceAll("");
//		} catch (Exception e) {
//			System.err.println(e.getMessage());
//		}
//		//返回文本字符串
//		return htmlStr;
	}
}
